
import xml.etree.ElementTree as ET
import os
from PIL import Image, ImageDraw, ImageFont
 
 
def parse_rec(pic_path, filename):
    """解析xml"""
    tree = ET.parse(filename)  # 解析读取xml函数
    objects = []
    img_dir = []
    coordinate = []
    for xml_name in tree.findall('******'):
        img_path = os.path.join(pic_path, xml_name.text)
        img_dir.append(img_path)
    for obj in tree.findall('object'):
        obj_struct = {'name': obj.find('name').text, 'pose': obj.find('pose').text,
                      'truncated': int(obj.find('truncated').text), 'difficult': int(obj.find('difficult').text)}
        bbox = obj.find('bndbox')
        obj_struct['bbox'] = [int(bbox.find('***').text),
                              int(bbox.find('***').text),
                              int(bbox.find('***').text),
                              int(bbox.find('***').text)]
        objects.append(obj_struct)
    for obj_one in objects:
        *****
        *****
        *****
        *****
        *****
        coordinate.append([*****,*****,*****,*****,*****])
    return coordinate, img_dir
 
 
def visualise_gt(objects, img_dir, now_path, font):
    """可视化"""
    for _, img_path in enumerate(img_dir):
        img = Image.open(img_path)
        draw = ImageDraw.ImageDraw(img)
        for obj in objects:
            xmin = obj[0]
            ymin = obj[1]
            xmax = obj[2]
            ymax = obj[3]
            label = obj[4]
            draw.rectangle((********), fill=None, outline="red")
            draw.text((xmin + 10, ymin), label, "blue", font=font)  # 利用ImageDraw的内置函数，在图片上写入文字
            img.save(os.path.join(now_path + '/' + os.path.split(img_path)[-1]))
        
 
 
if __name__ == "__main__":
    
    pic_path = ****
   
    ann_path = ****
   
    now_path = ****

    fontPath = ****
    font = ImageFont.truetype(fontPath, 20)
 
    for filename in os.listdir(ann_path):
        xml_path = os.path.join(ann_path, filename)

        obj_context, img_dir = parse_rec(pic_path, xml_path)

        visualise_gt(obj_context, img_dir, now_path, font)